#include <boost/algorithm/string/trim.hpp>
#include <unicode/ustream.h>
#include "AttchFilenameCond.h"
#include "../../utils/UnicodeStringComparer.h"

using namespace kc_sf;
using boost::algorithm::trim_copy;

// --------------------------------------------------------- //

AttchFilenameCond::AttchFilenameCond( Operator op, const std::string &name, bool ext )
: c_name_operator( op ),
  c_name( UnicodeString( boost::trim_copy( name ).c_str() ) ),
  c_check_only_ext( ext )
{
}

// --------------------------------------------------------- //

AttchFilenameCond::AttchFilenameCond( const AttchFilenameCond &cond )
{
	c_name_operator = cond.c_name_operator;
	c_name = cond.c_name;
	c_check_only_ext = cond.c_check_only_ext;
}

// --------------------------------------------------------- //

AttchFilenameCond AttchFilenameCond::operator=( const AttchFilenameCond &cond )
{
	if( &cond != this )
	{
		c_name_operator = cond.c_name_operator;
		c_name = cond.c_name;
		c_check_only_ext = cond.c_check_only_ext;
	}
	return *this;
}

// --------------------------------------------------------- //

bool AttchFilenameCond::eval( const Attachment &attch )
{
	UnicodeStringComparer *comparer = c_check_only_ext
			?	new UnicodeStringComparer( UnicodeString( attch.getExtension().c_str() ) )
			: new UnicodeStringComparer( UnicodeString( attch.getFilename().c_str() ) );

	bool success = c_name_operator == EqualMatch ? comparer->matches( c_name )
		: c_name_operator == NotEqualMatch ? !comparer->matches( c_name )
		: c_name_operator == HasWord ? comparer->contains( c_name )
		: c_name_operator == NotHasWord ? !comparer->contains( c_name )
		: c_name_operator == RegexMatch ? comparer->matchesRegex( c_name )
		: c_name_operator == NotRegexMatch ? !comparer->matchesRegex( c_name )
		: c_name_operator == ContainsRegex ? comparer->containsRegex( c_name )
		: c_name_operator == NotContainsRegex ? !comparer->containsRegex( c_name )
		: false;

	delete comparer;
	return success;
}
